package com.example.xf.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.nui.multiphotopicker.view.ImageBucketChooseActivity;
import com.yanzhenjie.album.Album;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import xf.tools.CropOption;
import xf.tools.CropOptionAdapter;
import xf.tools.Other;
import xf.tools.popu.SelectPicPopupWindow_Test;

/**
 * 测试界面
 */
public class MyActivity extends Activity {

    Button button1;

    Button button2;

    Button button3;

    ImageView imageView1;

    private Uri mImageCaptureUri;

    private static final int PICK_FROM_CAMERA = 1;
    private static final int CROP_FROM_CAMERA = 2;
    private static final int PICK_FROM_FILE = 3;

    private SelectPicPopupWindow_Test popupWindow_Test;

    @Override
    protected void onResume() {
        BaseActivity.activity = this; // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.myactivity);

        BaseActivity.activity = this;
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        imageView1 = (ImageView) findViewById(R.id.imageView1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Album.camera(MyActivity.this).start(PICK_FROM_CAMERA);
            }
        });
        button2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                EmmApplication.setData("Picture", "1");
                startActivity(new Intent(MyActivity.this, ImageBucketChooseActivity.class));
            }
        });
        button3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow_Test = new SelectPicPopupWindow_Test(MyActivity.this, keyListener);
                popupWindow_Test.showAtLocation(button1, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.w("a", +requestCode + "resultCode===" + resultCode + "RESULT_OK======" + RESULT_OK);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case PICK_FROM_CAMERA:
                Log.e("a", "拍照");
                doCrop();
                break;
            case PICK_FROM_FILE:
                Log.e("a", "相册");
                // selectImage(PicActivity.this, data);
                mImageCaptureUri = data.getData();
                doCrop();
                break;
            case CROP_FROM_CAMERA:
                Log.e("CROP_FROM_CAMERA", "CROP_FROM_CAMERA");
                if (null != data) {
                    saveCutPic(data);
                }
                break;
            case 0:
                System.out.println("相册");
                break;
            default:
                break;
        }
    }

    private void doCrop() {
        final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");
        List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
        int size = list.size();
        Toast.makeText(this, "Can not find image crop app额" + size, Toast.LENGTH_LONG).show();
        if (size == 0) {
            Toast.makeText(this, "Can not find image crop app啊", Toast.LENGTH_SHORT).show();
            return;
        } else {
            intent.setData(mImageCaptureUri);
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);
            intent.putExtra("return-data", true);
            if (size == 1) {
                Intent i = new Intent(intent);
                ResolveInfo res = list.get(0);
                i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                startActivityForResult(i, CROP_FROM_CAMERA);
            } else {
                for (ResolveInfo res : list) {
                    final CropOption co = new CropOption();

                    co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                    co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                    co.appIntent = new Intent(intent);

                    co.appIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                    cropOptions.add(co);
                }

                CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Choose Crop App");
                builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        startActivityForResult(cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
                    }
                });

                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {

                        if (mImageCaptureUri != null) {
                            getContentResolver().delete(mImageCaptureUri, null, null);
                            mImageCaptureUri = null;
                        }
                    }
                });

                AlertDialog alert = builder.create();

                alert.show();
            }
        }
    }

    private void saveCutPic(Intent picdata) {
        // selectImage(getApplicationContext(), picdata);
        Bundle bundle = picdata.getExtras();
        if (null != bundle) {
            Bitmap mBitmap = bundle.getParcelable("data");
            imageView1.setImageBitmap(mBitmap);
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                mBitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
                byte[] datas = baos.toByteArray();
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                byte[] encode = Base64.encode(datas, Base64.DEFAULT);
                String photo2 = new String(encode);
                EmmApplication.setData("uri_byte", photo2);
                Log.e("phone_date", photo2);
                sendBroadcast(new Intent(Other.VGOPLAY_1));
                finish();
            } catch (Exception e) {
            }
        }
        File f = new File(mImageCaptureUri.getPath());

        if (f.exists()) {
            f.delete();
        }
    }

    OnClickListener keyListener = new OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.imageView1:

                    if (TextUtils.isEmpty(popupWindow_Test.getType()) || TextUtils.isEmpty(popupWindow_Test.getType_One())) {
                        EmmApplication.T("亲，您选择的地址有误，请重新选择");
                    } else {
                        button3.setText(popupWindow_Test.getLanguage() + popupWindow_Test.getType() + popupWindow_Test.getType_One());

                        EmmApplication.areaIds = popupWindow_Test.getareaId_one() + "|" + popupWindow_Test.getareaId_two() + "|"
                                + popupWindow_Test.getareaId_three();
                    }
                    Log.w("areaIds:", EmmApplication.areaIds);
                    popupWindow_Test.dismiss();
                    break;
                default:
                    break;
            }

        }

        ;

    };

}
